/**
 * @作者：耿
 * @时间：2022-11-05
 */

import { observable, configure, action, runInAction, makeAutoObservable, computed, autorun  } from 'mobx'
import axios from 'axios'

//面向对象方式初始化 （class 方式）
class CartStore {
    constructor() {
        makeAutoObservable(this)
        // 创建 autorun 来监听 cartProd 数组的变化
        autorun(() => {
            this.updateTotalPrice();
        });
    }

    // 计算总价格
    updateTotalPrice() {
        console.log('updateTotalPrice')
        this.totalPrice = this.cartProd.reduce((total, product) => {
            return total + product.price * product.num;
        }, 0);
        console.log('this.totalPrice ', this.totalPrice )

    }

    @observable is = true  //@ ES7 装饰器语法， java中是注解 
    @observable name = 'geng'
    @observable list = []
    @observable cartProd = []
    //购物车商品总数，计算属性
    @computed get totalNum() {
        return this.cartProd.length;
    }
    @observable totalPrice = 0

    @action addCart(product) {
        this.cartProd.push(product)
    }

    @action delCart(obj) {
        this.cartProd.push(obj)
    }

    @action getList() {
        let _this = this;
        axios.get('http://localhost:3000/users').then(
            res => {
                if (res.status === 200) {
                    runInAction(() => {
                        // _this.list = res.data
                        this.list = [{
                            id: 1,
                            name: '耐克',
                            price: 20,
                            num: 1
                        }, {
                            id: 2,
                            name: '阿迪',
                            price: 20,
                            num: 1
                        }]

                    })
                }
            },
            err => {
                console.log('err', err)
            }
        )
    }

}

//初始化对象
const cartStore = new CartStore()

export default cartStore